package controller
{
	import com.adobe.webapis.flickr.FlickrService;
	import com.adobe.webapis.flickr.License;
	import com.adobe.webapis.flickr.PagedPhotoList;
	import com.adobe.webapis.flickr.Photo;
	import com.adobe.webapis.flickr.events.FlickrResultEvent;
	
	import flash.system.Security;
	
	import view.ThumnailView;
	
	import mx.collections.ArrayCollection;
	
	import spark.components.Image;
	
	public class FlickrUtil
	{
		public static var PHOTOS_PER_PAGE:Number = 20;
		private static var FLICKR_API_KEY:String = "a82c7a50cb4ee2d629e0389d97f75c61";
		private static var FLICKR_API_SECRET:String = "899522b55966f151";
		private static var APP_LICENSE:Number = License.ATTRIBUTION_NONCOMMERCIAL;
		private var flickrService:FlickrService = new FlickrService(FLICKR_API_KEY);
		[Bindable] public var lastSearch:String = "";
		[Bindable] public var pagedPhotoList:PagedPhotoList;
		[Bindable] public var photos:ArrayCollection;
		
		public function FlickrUtil()
		{
			/*Security.allowDomain(["api.flickr.com", "flickr.com", "*"]);
			Security.allowInsecureDomain(["api.flickr.com", "flickr.com", "*"]);*/
		}
		
		public function searchImages(searchText:String, page:Number):void
		{
			this.lastSearch = searchText;
			this.flickrService.addEventListener(FlickrResultEvent.PHOTOS_SEARCH, onPhotosSearch);
			this.flickrService.photos.search("", searchText, "any", "", null, null, null, null, APP_LICENSE, "", PHOTOS_PER_PAGE, page, "date-posted-desc");
		}
		
		public function nextPage():void
		{
			if (this.photos.length == PHOTOS_PER_PAGE)
			{
				searchImages(this.lastSearch, this.pagedPhotoList.page + 1);
			}
		}
		
		public function previousPage():void
		{
			if (this.pagedPhotoList.page != 1)
			{
				searchImages(this.lastSearch, this.pagedPhotoList.page - 1);
			}
		}
		
		private function onPhotosSearch( event:FlickrResultEvent ):void {
			this.flickrService.removeEventListener(FlickrResultEvent.PHOTOS_SEARCH, onPhotosSearch);
			if (event.success)
			{
				this.pagedPhotoList = event.data.photos;
				reloadImages();
			}
		}
		
		private function reloadImages():void
		{
			var images:ArrayCollection = new ArrayCollection;
			for each (var photo:Photo in this.pagedPhotoList.photos) 
			{
				var imageModel:ThumnailView = new ThumnailView(photo);
				images.addItem(imageModel);
			}
			photos = images;
		}
	}
}